import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhouyanxiang
 * @create 2020-11-2020/11/1-20:43
 * <h1>负载均衡之哈希法</h1>
 */
public class Solution {

    static Map<String, Integer> map = new ConcurrentHashMap<>();

    static {
        map.put("192.168.1.12",1);
        map.put("192.168.1.13",2);
        map.put("192.168.1.14",4);
    }

    public String random(String clientIp) {
        Map<String, Integer> ipMap = new ConcurrentHashMap<>(map);
        Set<String> set = ipMap.keySet();
        List<String> list = new ArrayList<>(set);

        // 计算得到哈希值
        int hashCode = clientIp.hashCode();
        int serverListSize = list.size();
        // 取模
        int pos = hashCode % serverListSize;
        return list.get(pos);
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.random("192.168.2.22"));
    }
}
